package org.nowcoder.leetcode.twoPointers;

import java.util.HashMap;
import java.util.Map;

/**
 * Title  : 1. Two Sum
 * Source : https://leetcode.cn/problems/two-sum/
 * Author : XrazYang
 * Date   : 2023-05-31
 * 其他相关题目   ：15. 3Sum  18. 4Sum  167. Two Sum II - Input Array Is Sorted
 */
public class LeetCode_1 {
    public int[] twoSum(int[] nums, int target) {
        //暴力求解
//        for (int i = 0; i < nums.length; i++) {
//            for (int j = i + 1; j < nums.length; j++) {
//                if (target == nums[i] + nums[j]) {
//                    return new int[]{i, j};
//                }
//            }
//        }
//        return null;

        //哈希表
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }
}
